#include "DaterOfflineMessage.h"
#include "DaterLinktoSQL.h"

namespace Dater
{
	template<> OfflineMessage* Singleton<OfflineMessage>::ms_Singleton = 0;

	OfflineMessage::OfflineMessage(): _delimiter('\b'), _selectResultDelimiter('\t'), 
		linktosql(),_user("root"),_password("19920418")
	{
		linktosql.ConnMySQL("localhost", "3306", "dater", (char*)_user.c_str(), (char*)_password.c_str() , "GBK", "");

		std::string sqlResult = linktosql.SelectData("select uid from user;", 1, linktosql.Msg, _selectResultDelimiter, _delimiter);
		linktosql.CloseMySQLConn();

		std::vector<std::string> dividedSqlResult;

		split(sqlResult, _selectResultDelimiter, dividedSqlResult);
		for(unsigned index1 = 0; index1 < dividedSqlResult.size(); index1++)
		{
			std::vector<std::string> temMessageVector;
			_offlineMessage[atoi(dividedSqlResult[index1].c_str())] = temMessageVector;
		}
	}
		
	void OfflineMessage::addUser(int uid)
	{
		if(_offlineMessage.find(uid) == _offlineMessage.end())
		{
			std::vector<std::string> temMessageVector;
			_offlineMessage[uid] = temMessageVector;
		}
	}

	void OfflineMessage::pushOfflineMessage(int uid, std::string msg)
	{
		if(_offlineMessage.find(uid) != _offlineMessage.end())
		{
			_offlineMessage[uid].push_back(msg);
		}
	}

	void OfflineMessage::popOfflineMessage(int uid)
	{
		if(_offlineMessage.find(uid) != _offlineMessage.end())
		{
			if(_offlineMessage[uid].size() != 0)
			{
				_offlineMessage[uid].erase(_offlineMessage[uid].begin());
			}
		}
	}

	void OfflineMessage::clearOfflineMessage(int uid)
	{
		if(_offlineMessage.find(uid) != _offlineMessage.end())
		{
			_offlineMessage[uid].clear();
		}
	}

	bool OfflineMessage::isOfflineMessageEpmty(int uid)
	{
		if(_offlineMessage.find(uid) != _offlineMessage.end())
		{
			return _offlineMessage[uid].empty();
		}else
			return true;
	}

	std::string OfflineMessage::getOfflineMessage(int uid)
	{
		if(_offlineMessage.find(uid) != _offlineMessage.end())
		{
			if(_offlineMessage[uid].size() != 0)
				return _offlineMessage[uid].front();
		}

		return "";
	}

	void OfflineMessage::split(std::string const& order, char delimiter, std::vector<std::string>& splitedVector)
	{
		splitedVector.clear();

		if(order.size() == 0)
			return;

		std::string::size_type pos = 0, pre_pos = 0;

		while((pos = order.find_first_of(delimiter, pos)) != std::string::npos)
		{
			splitedVector.push_back(order.substr(pre_pos, pos - pre_pos));
			pre_pos = ++pos;
		}

		splitedVector.push_back(order.substr(pre_pos, pos - pre_pos));

	}
}